// pages/order/modify-order/index.js
const dayjs = require('dayjs')
const { default: Notify } = require('../../../miniprogram_npm/@vant/weapp/notify/notify')
import { saveWorkOrderModify } from "../../../api/order";
Page({

  /**
   * 页面的初始数据
   */
  data: {
    orderData: {
      xmbzNo: '1',
      address1: '2',
    },
    newAddress: {
      address: '',
    },
    showMap: false,
    newTime: {
      delySTime: '',
      delyETime: '',
    },
    timeList: [],
    reasonList: ['卡点已沟通延迟','真实号码收不到短信','真实号码回复失败','联系不上已沟通延迟','虚拟号修改时间','客户修改地址','定位错误']

  },

  onShowMap() {
    this.setData({
      showMap: true,
    })
  },
  // 地图选择
  handleMapSelect(e) {
    const {address} = e.detail
    this.setData({
      newAddress: {
        address: address.name,
        longitude: address.longitude,
        latitude: address.latitude,
      },
      showMap: false,
    })
  },
  handleMapCancel() {
    this.setData({
      showMap: false,
    })
  },

  // 加载时间列表
  initTime() {
    let start = dayjs().format('HH');
    let dataList = [];
    for (let i = Number(start) + 1; i < 24; i++) {
      dataList.push({
        startTime: i + ':00',
        endTime: i == 23 ? i + ':59' : i + 1 + ':00',
        isChecked: false,
      });
    }
    this.setData({
      timeList: dataList
    })
  },

  handleCheckTime(e) {
    const {timeList} = this.data;
    const {item} = e.currentTarget.dataset;
    timeList.forEach(i => {
      if (i.startTime === item.startTime) {
        i.isChecked = true;
      } else {
        i.isChecked = false;
      }
    })
    this.setData({
      timeList: timeList,
      newTime: {
        delySTime: item.startTime,
        delyETime: item.endTime
      }
    })
  },

  cancel() {
    wx.navigateBack()
  },

  confirm() {
    const valid = this.validateParams();
    if (!valid) {
      return;
    }
    const params = this.getParams();
    saveWorkOrderModify(params).then(res => {
      if (res.data.code == 200) {
        wx.showLoading({
          title: '提交成功',
        })
        wx.navigateBack();
      } else {
        Notify({
          message: `${res.data.msg}`,
          type: 'danger'
        })
      }
    })
  },
  // 校验参数
  validateParams() {
    const {newAddress,newTime} = this.data
    if (!newAddress.longitude && !newTime.delySTime) {
      Notify({
        message: '无修改内容',
        type: 'danger'
      })
      return false
    }
    const reasonDom = this.selectComponent(`#reasonPicker`)
    if (reasonDom) {
      const checkedReason = reasonDom.getCheckedItem();
      if (!checkedReason.checked) {
        Notify({
          message: '请选择修改原因',
          type: 'danger'
        })
        return false;
      }
    }
    return true
  },
  getParams() {
    const {orderData, newAddress, newTime} = this.data;
    const reasonDom = this.selectComponent(`#reasonPicker`)
    const checkedReason = reasonDom.getCheckedItem();
    const extJson = {};
    if (newAddress.address) {
      extJson['receiverAddress'] = newAddress.address;
      extJson['longitude'] = newAddress.longitude;
      extJson['latitude'] = newAddress.latitude;
    }
    if (newTime.delySTime) {
      const year = new Date().getFullYear();
      extJson['deliveryStartTime'] = `${year}-${orderData.delyTime} ${newTime?.delySTime}:00`;
      extJson['deliveryEndTime'] = `${year}-${orderData.delyTime} ${newTime?.delyETime}:${newTime?.delyETime.includes('59') ? '59' : '00'}`;
    }
    const params = {
      orderId: orderData.ordNo,
      platformOrderId: orderData.platformOrderId,
      xmbzNo: orderData.xmbzNo,
      cityId: orderData.cityId,
      cityName: orderData.cityName,
      reason: checkedReason.checked,
      extJson: JSON.stringify(extJson)
    }
    return params
  },
  // 地址
  onAddressChange(e) {
    const {newAddress} = this.data
    const value = e.detail;

    this.setData({
      newAddress: {
        ...newAddress,
        address: value
      }
    })
  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
      //	获取所有打开的EventChannel事件
     const eventChannel = this.getOpenerEventChannel();
     // 监听 index页面定义的 toB 事件
     eventChannel.on('modify-order', (res) => {
       this.setData({
        orderData: res.orderData
       })
     })
     this.initTime();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})